package com.angel.email.services.impl;

import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;

import com.angel.email.builder.EmailBuilder;
import com.angel.email.configuration.EmailConfiguration;
import com.angel.email.configuration.builders.EmailConfigurationBuilder;
import com.angel.email.configuration.builders.IncomingEmailConfigurationBuilder;
import com.angel.email.connection.IncomingEmailConnection;
import com.angel.email.exceptions.EmailSendlException;
import com.angel.email.response.EmailMessagesResponse;
import com.angel.email.services.EmailService;

/**
 *
 * @author William
 *
 */
public class EmailServiceImpl implements EmailService {

	public void sendEmail(Email email) {
		try {
			email.send();
		} catch (EmailException e) {
			throw new EmailSendlException("An error occured sending email from [" + email.getFromAddress().getAddress() + "] at [" + email.getSentDate() + "].", e);
		}
	}

	public void sendEmail(EmailBuilder emailBuilder) {
		Email email = emailBuilder.buildEmail();
		this.sendEmail(email);
	}

	public EmailMessagesResponse receivedEmailsFrom(String folderName, Integer maximumQuantity, IncomingEmailConfigurationBuilder incomingEmailConfigurationBuilder){
		EmailConfigurationBuilder ecb = new EmailConfigurationBuilder(Boolean.FALSE);
		ecb.setIncomingConfigurationBuilder(incomingEmailConfigurationBuilder);
		EmailConfiguration emailConfiguration = ecb.buildEmailConfiguration();
		IncomingEmailConnection emailConnection = emailConfiguration.connectToIncomingEmail();
		EmailMessagesResponse messages = emailConnection.getMessagesForFolder(folderName, maximumQuantity);
		return messages;
	}
}
